#ifndef FILESERVER_H
#define FILESERVER_H


#include <iostream>
#include "Server.h"
#include <pthread.h>
#include <vector>

using namespace std;

#include "muscle/message/Message.h"

using namespace muscle;


struct ClientInfo
{
	int id;
	Server* server;
};



static void* HandleClient(void* clientInfo){
ClientInfo* ci = (ClientInfo*)clientInfo;
			int cid = ci->id;
			Server* server = ci->server;
		 while(true){

			
			uint32 messageSize;

			int size = server->Receive(cid, &messageSize, sizeof(int));

			if(size == -1){
			cout<<"client disconnected" << endl;
			break;
			}

			uint8 buffer[messageSize];

			if(server->Receive(cid, buffer, messageSize) < 1){
				cout<< "client disconnected" << endl;
				break;
			}

			Message m;

			if(B_ERROR == m.Unflatten(buffer, size)){
				cout<< "Error unflattening" << endl;
			}

			String OperationString;

			String FileOperation("FileOperation");	

			if(m.FindString(FileOperation, OperationString)== B_NO_ERROR){
				cout<< OperationString.Cstr() << endl;
			}
			else{
				cout<< "MessageError:Could not find string" << endl;
			}
		}
	}

class FileServer{

	Server* m_server;

	pthread_t* threads[100];

	

public:

	FileServer(int port){
		cout<< "Listening on port " << port << endl;
		m_server = new Server(port, "tcp", 4);
	}

	~FileServer(){
		delete m_server;
	}

	void Start(){
	
		//server starts listening
		m_server->Listen();

		while(true){		

			//server accepts connection
  			int id = m_server->Accept();

			threads[id] = new pthread_t();

			ClientInfo ci;
			ci.id = id;
			ci.server = m_server;
			if(0 != pthread_create(threads[id], NULL, HandleClient, &ci)){
				cout<< "Thread Creation Failed" << endl;
			}
			else{
				cout<< "New Client Proxy Created. Client id is " << ci.id << endl;
			}

		}

	}



};


#endif

